package com.cn.wanxi.servlet.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cn.wanxi.model.*;
import com.cn.wanxi.service.IProductService;
import com.cn.wanxi.service.IProductTypeService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.service.impl.ProductTypeServiceImpl;
import com.cn.wanxi.util.DataEncoding;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {
    IProductTypeService productTypeService = new ProductTypeServiceImpl();
    IProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect(DataField.LOCALHOST_PORT+"/html/front/product.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        List<ProductTypeModel> productTypeList = productTypeService.getProductTypeList();
        int page = Integer.parseInt(req.getParameter("page"));
        int pdt_type = Integer.parseInt(req.getParameter("product_type"));
        Map<String,Object> map = new HashMap<>();
        map.put("page",(page-1)* DataField.PRODUCT_SIZE);
        map.put("size",DataField.PRODUCT_SIZE);
        map.put("product_type",pdt_type);
        List<ProductModel> productList = productService.getProductList(map);
        long pageCount = productService.getProductListCount(map);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("productTypes",productTypeList);
        jsonObject.put("products",productList);
        jsonObject.put("pageCount",pageCount);
        jsonObject = JSON.parseObject(JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        resp.getWriter().print(jsonObject);
    }
}
